#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/in.h>

#define PORT 8888
#define BACKLOG 3
void process_conn_server(int s);
int main()
{
	int ss ,sc;
	
	struct sockaddr_in server;
	struct sockaddr_in client;
	int err;
	pid_t pid;
	
	ss = socket(AF_INET,SOCK_STREAM,0);
	if(ss<0)
	{	
		printf("socket error");
		return -1;
	}
	
	bzero(&server ,sizeof(server));

	server.sin_family=AF_INET;
	server.sin_addr.s_addr=htonl(INADDR_ANY);
	server.sin_port=htons(PORT);
	err =bind(ss,(struct sockaddr*)&server, sizeof(server));
	if(err<0)
	{
		printf("bind error!");
		return -1;
	}	
	err = listen(ss ,BACKLOG);
	if(err<0)
	{
		printf("listen err!");
		return -1;
	}	
	
	while(1)
	{
		int addrlen = sizeof(client);
		sc  =accept(ss , (struct sockaddr*)&client ,  &addrlen);
		if(sc<0)
		{
			printf("accept error!");
			continue;
		}
		
		pid = fork();
		if(pid ==0 )
		{
			close(ss);
			process_conn_server(sc);
		}else{
			close(sc);		
		}
		
	}

}



void process_conn_server(int s)
{
	ssize_t size =0;
	char buffer[1024];
	while(1)
	{
		size =read(s,buffer,1024);	
		if(size==0)
			return;
		buffer[size+1]='\0';
		printf("server receive %s",buffer);
		sprintf(buffer,"%d bytes alltoger \n",size);
		write(s,buffer,strlen(buffer)+1);
	}
}

